package com.imooc.alllearning.util;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Date;

/**
 * @Author: crowsjian
 * @Date: 2020/4/2 21:02
 */
@Slf4j
public class LocalDateTimeStringConverter implements Converter<Date> {
    @Override
    public Class supportJavaTypeKey() {
        return Date.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Date convertToJavaData(CellData cellData,
                                  ExcelContentProperty excelContentProperty,
                                  GlobalConfiguration globalConfiguration) throws Exception {
        return null;
    }

    @Override
    public CellData convertToExcelData(Date date,
                                       ExcelContentProperty excelContentProperty,
                                       GlobalConfiguration globalConfiguration) throws Exception {
        if(excelContentProperty==null||excelContentProperty.getDateTimeFormatProperty()==null){
            //默认格式化格式
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            return new CellData(formatter.format(date));
        }else{
            //自定义格式化格式
            return new CellData(DateTimeFormatter.ofPattern(excelContentProperty
                    .getDateTimeFormatProperty().getFormat()).format((TemporalAccessor) date));
        }
    }
}
